<?php

declare(strict_types=1);

namespace App\Services\Orders;

use App\Exception\InvalidRequestException;
use App\Services\Goods\Good;
use App\Utils\Services\BaseServices;
use App\Model\Orders\Order as OrderModel;
use App\Services\Users\User as UserServices;
use Hyperf\Database\Model\ModelNotFoundException;
use Hyperf\DbConnection\Db;
use function Hyperf\Support\make;

/**
 * Class Order
 * @author zx
 * @package App\Services\Orders
 */
Class Order extends BaseServices
{
    /**
     * 模型
     * @return string
     */
    public function model():string
    {
        return OrderModel::class;
    }

    /**
     * 下单
     * @param array $params
     * @return OrderModel
     */
    public function setOrder(array $params)
    {
        /** @var OrderModel $model */
        $this->setModel($this->model());
        $params['no'] = $this->getModel()->getNo();

        /** @var UserServices $userServices */
        $userServices = make(UserServices::class);
        $userModel = $userServices->register($params);
        /** @var Good $goodServices */
        $goodServices = make(Good::class);
        $goodsModel = $goodServices->whereIn('product_id', array_column($params['goods'], 'product_id'))->get();

        return Db::transaction(function () use ($userModel, $params, $goodsModel) {
            $params['user_id'] = $userModel->id;
            /** @var OrderModel $orderModel */
            if ($params['source'] === 'mini' && !$params['jump']) {
                $params['payer_name'] = $params['payer']['name'];
                $params['payer_no'] = $params['payer']['id_card'];
                $params['payer_mobile'] = $params['payer']['mobile'];
                $params['payer']['openid'] = $params['open_id'];
                $params['payer']['app_id'] = $params['appid'];
            }
            $orderModel = $this->create($params);
            if (!$orderModel->exists) {
                throw new InvalidRequestException();
            }
            $orderGoodsData = [];

            $goodsPluck = $goodsModel->pluck('product_id');
            foreach ($params['goods'] as $good) {
                $key = $goodsPluck->search($good['product_id']);
                if (false === $key) {
                    throw new ModelNotFoundException();
                }
                $goodData = $goodsModel->get($key);
                $goodData['goodsImg'] = $goodData['image'];
                $goodData['goodsName'] = $goodData['name'];
                $good['good'] = $goodData;
                $good['good_no'] = $goodData['no'];
                $good['product_id'] = $goodData['product_id'];
                $good['barcode'] = $goodData['barcode'];
                $orderGoodsData[] = $good;
            }

            $orderModel->goods()->createMany($orderGoodsData);

            return $orderModel;
        });
    }
}
